<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议 https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\api\controller\system;

use app\admin\service\TriggerService;
use app\common\controller\AdminController;
use app\common\service\AgentApiService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use app\admin\service\NodeService;
use think\App;
use think\Model;
use app\admin\model\SystemConfig;
use app\common\service\ApiService;
use think\facade\Cache;
/**
 * @ControllerAnnotation(title="配置管理")
 * Class Node
 *
 * @package app\admin\controller\system
 */
class Config extends AdminController
{

    /**
     * 字段排序
     *
     * @var array
     */
    protected $sort = [
        'role_id' => 'desc'
    ];
    
    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\SystemConfig();
    }

    /**
     * @NodeAnotation(title="系统设置")
     */
    public function query()
    {
        $request = $this->request;
        $group = $request->param("group");
        $data = sysconfig($group);
        
        if ($group == 'template') {
            $list = $this->gettemplatelist();
            $industry = $this->getindustry();
            $industrytext = '';
            if ($industry && is_array($industry)) {
                foreach ($industry as $indu) {
                    if ($indu && is_array($indu)) {
                        foreach ($indu as $i) {
                            $industrytext .= $i['name'] . '   ';
                        }
                    }
                }
            }
            $data['set'] = $data;
            $data['industrytext'] = $industrytext;
            $data['list'] = $list;
        }
        
        if ($group == 'account') {
            if (! empty(sysconfig('account', 'account_appid')) && ! empty(sysconfig('account', 'account_appsecret'))) {
                if (sysconfig('account', 'operation_version') ==1 ){
                    $apiService = new ApiService();
                    $rtn = $apiService->info();
                }else{
                    $apiService = new AgentApiService();
                    $rtn = $apiService->info();

                }

                if ($rtn['code']) {
                    $data['data'] = $rtn['data'];
                } else {
                    $data['msg'] = $rtn['msg'];
                }
            }
        }
        
        return msg($data, 0, "查询成功");
    }

    public function logList()
    {
        if (empty(sysconfig('account', 'account_appid')) || empty(sysconfig('account', 'account_appsecret'))) {
            return msg([], 1, 'fail');
        }
        
        $page = input("page");
        $limit = input("limit");
        
        $apiService = new ApiService();
        $result = $apiService->log([
            'page' => $page,
            'psize' => $limit
        ]);
        
        if (isset($result['code']) && $result['code'] == 1) {
            return msg([
                'list' => $result['data']['list'],
                'count' => $result['data']['total']
            ], 0, "查询成功");
        } else {
            return msg([], 1, $result['msg']);
        }
    }

    /**
     * @NodeAnotation(title="保存")
     */
    public function save()
    {
        $post = $this->request->post();
        if ( isset($post['upload_describe'])&& ! empty($post['upload_describe'])) {
            $post['upload_describe'] = htmlspecialchars_decode($post['upload_describe']);
        }

        if ( isset($post['copywriting_require'])&& ! empty($post['copywriting_require'])) {
            $post['copywriting_require'] = htmlspecialchars_decode($post['copywriting_require']);
        }
        if ( isset($post['link_require'])&& ! empty($post['link_require'])) {
            $post['link_require'] = htmlspecialchars_decode($post['link_require']);
        }
        try {

            foreach ($post as $key => $val) {
                SystemConfig::where('name', $key)->update([
                    'value' => $val
                ]);

                if ($key == 'account_appid') {
                    if ($val != sysconfig('account', 'account_appid')) {
                        SystemConfig::where('name', 'account_token')->update([
                            'value' => ''
                        ]);

                        SystemConfig::where('name', 'account_expires_in')->update([
                            'value' => ''
                        ]);
                    }
                }
            }
            Cache::clear();
            TriggerService::updateSysconfig();
        }catch (\Exception $e) {
            return msg([], 1, "保存失败");
        }
        return msg([], 0, "保存成功");
    }

    public function getindustry()
    {
        $token = getAccessToken();
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token=' . $token;
        $c = httpGet($url);
        $result = json_decode($c, true);
        
        if (! is_array($result)) {
            return false;
        }
        
        if (! empty($result['errcode'])) {
            return false;
        }
        
        return $result;
    }

    public function gettemplatelist()
    {
        $token = getAccessToken();
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=' . $token;
        $c = httpGet($url);
        
        $result = json_decode($c, true);
        
        if (! is_array($result)) {
            return false;
        }
        
        if (! empty($result['errcode'])) {
            return false;
        }
        
        return $result['data'];
    }

    public function gettemplate()
    {
        $id = input('id');
        $list = $this->gettemplatelist();
        $template = NULL;
        
        foreach ($list as $temp) {
            if ($temp['template_id'] == $id) {
                $template = $temp;
                break;
            }
        }
        
        $this->assign('row', $template);
        return $this->fetch();
    }
}